<?php
class CustomerController extends Controller
{
    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionGetdata(){

        $page = $_REQUEST['page'];
        $rows = $_REQUEST['rows'];
        $start = ($page-1)*$rows;
        $total = $this->connection->createCommand("select count(1) from crm_customer where deleted = 0 ")->queryScalar();
        $result = $this->connection->createCommand("select * from crm_customer where deleted = 0  limit {$rows} offset {$start}")->queryAll();

        $data = Array();
        $data['total'] = $total;
        $data['rows'] = $result;

        echo json_encode($data);
    }

    public function actionShowedit(){

        $customer_id = $_REQUEST['customer_id'];

        $customer = null;
        if($customer_id==0){
            //新增
        }else{
            //编辑
            $customer = $this->connection->createCommand("select * from crm_customer where customer_id = :customer_id")->bindParam(':customer_id',$customer_id,PDO::PARAM_INT)->queryRow();
        }

        $this->render('showedit',['customer'=>$customer]);
    }

    public function actionSavedata(){

        $customer_id = $_REQUEST['customer_id'];
        $customer_name = $_REQUEST['customer_name'];
        $phone = $_REQUEST['phone'];
        $status = $_REQUEST['status'];

        if($customer_id!=null){
            //编辑
            $this->connection->createCommand("update crm_customer set customer_name = :customer_name,phone = :phone,status=:status where customer_id = :customer_id")
                ->bindParam(':customer_id',$customer_id,PDO::PARAM_INT)
                ->bindParam(':customer_name',$customer_name,PDO::PARAM_STR)
                ->bindParam(':phone',$phone,PDO::PARAM_INT)
                ->bindParam(':status',$status,PDO::PARAM_INT)
                ->execute();
        }else{
            //添加
            $this->connection->createCommand("insert into crm_customer (customer_name,phone,status) values (:customer_name,:phone,:status) ")
                ->bindParam(':customer_name',$customer_name,PDO::PARAM_STR)
                ->bindParam(':phone',$phone,PDO::PARAM_INT)
                ->bindParam(':status',$status,PDO::PARAM_INT)
                ->execute();
        }
    }

    public function actionRemove(){
        $customer_id = $_REQUEST['customer_id'];
        $this->connection->createCommand("update crm_customer set deleted = 1 
where customer_id = :customer_id")
            ->bindParam(':customer_id',$customer_id,PDO::PARAM_INT)
            ->execute();
    }

    public function actionView(){

        $customer_id = $_REQUEST['customer_id'];
        $customer = $this->connection->createCommand("select * from crm_customer where customer_id = :customer_id")->bindParam(':customer_id',$customer_id,PDO::PARAM_INT)->queryRow();

        $this->render('view',['customer'=>$customer]);
    }

}